<?php

namespace App\Http\Controllers\Source\Rong360;

use App\Events\AuthStepEvent;
use App\Events\R360GetCertPicEvent;
use App\Facades\SamLogFacade;
use App\Library\Tools\R360FieldTransfer;
use App\Models\R360UserBaseInfo;
use App\Models\RepaySummary;
use App\Models\User;
use App\Models\UserAuthStepEventLog;
use App\Models\UserCertOcr;
use App\Models\UserDeviceInfo;
use App\Models\UserGlobal;
use App\Models\UserInfo;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class UserController extends Controller
{
    /**
     * Description:可申请用户&复贷简化流程判断接口
     * Author: Sam
     * DateTime: 2019-02-22 16:10
     * @param Request $request
     * @return mixed
     */
    public function check(Request $request)
    {
        $data = $request->get('biz_data');
        $data = json_decode($data,true);
        $user = User::where('r360_check', $data['md5'])->first();
        if (!$user) {
            return r360Success('', ['data' => ['is_reloan' => 0]]);
        } else {
            $can = $user->canLoan();
            if(!$can){
                return r360fail('', ['reason' => 'C001']);
            }
            /**
             * 用户30天内有没有被拒绝过
             */
            $last_fail_time = UserGlobal::where('uid', $user->id)->value('last_request_fail_time');
            if ($last_fail_time) {
                $days = Carbon::parse($last_fail_time)->diffInDays(Carbon::now());
                if ($days < 30) {
                    return r360fail('', ['reason' => 'C003']);
                }
            }

            /**
             * 判断用户有没有逾期的还款
             */
            $over =  RepaySummary::getOverdueInformation($user->id);
            if (!$over) {
                return r360fail('', ['reason' => 'C002']);
            }

            /**
             * 判断用户有没有在360有已结清的订单
             */
            $source = RepaySummary::isPayOffFor360($user->id);
            if ($source) {
                return r360Success('', ['data' => ['is_reloan' => 1, 'verify_info' => [], 'other_info' => []]]);
            } else {
                return r360Success('', ['data' => ['is_reloan' => 0]]);
            }
        }
    }

    /**
     * Description:订单基本信息推送接口
     * Author: Sam
     * DateTime: 2019-03-04 15:56
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function baseInfo(Request $request)
    {
        $data = $request->get('biz_data');
        $data = json_decode($data,true);
        $order_info = $data['orderInfo'];
        $exist = Redis::get('base_info_'.$order_info['order_no']);
        if($exist){
            return r360Success('');
        }
        $user = User::where('phone_num', $order_info['user_mobile'])->first();
        $unique = UserLoanRequest::where(['source' => 'r360', 'trans_id' => $order_info['order_no']])->first();
        if ($unique) {
            return r360fail('订单已存在！');
        }
        DB::beginTransaction();
        try {
            if (!$user) {
                $user = User::create(['phone_num' => $order_info['user_mobile'], 'password' => bcrypt('123456'), 'source' => 'r360']);
            } else {
                $current_loan = UserLoanRequest::where(['user_id' => $user->id, 'current' => 1])->first();
                if ($current_loan) {
                    $current_loan->current = UserLoanRequest::CURRENT_BEFORE;;
                    $current_loan->save();
                }
            }
            $loan_info = [
                'user_id' => $user->id,
                'status' => 0,
                'current' => 1,
                'source' => 'r360',
                'trans_id' => $order_info['order_no'],
            ];
            /**
             * 生成授信记录
             */

            $loan = UserLoanRequest::create($loan_info);
            $apply_detail = $data['applyDetail'];
            $apply_detail['id_num'] = $apply_detail['user_id'];
            $apply_detail['user_id'] = $user->id;

            /**
             * 保存用户基础信息
             */
            R360UserBaseInfo::create($apply_detail);

            $cert_info = [
                'user_id' => $user->id,
                'name' => $order_info['user_name'],
                'num' => $apply_detail['id_num'],
            ];
            /**
             * 生成用户身份证信息
             */
            $ocr = UserCertOcr::create($cert_info);
            $log = [
                'uid'=>$user->id,
                'step_id'=>$ocr->id,
                'type'=>UserAuthStepEventLog::STEP_OCR,
                'loan_request_id'=>$loan->id,
            ];
            event(new AuthStepEvent($log));
            DB::commit();
            Redis::set('base_info_'.$order_info['order_no'],1);
            return r360Success('');
        } catch (\Exception $exception) {
            DB::rollBack();
            SamLogFacade::debug("r360基本信息推送接口失败：".$exception->getMessage());
            return r360fail('服务器错误！');
        }
    }

    /**
     * Description:补充信息推送接口
     * Author: Sam
     * DateTime: 2019-03-01 12:04
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function supplementInfo(Request $request)
    {
        $data = $request->get('biz_data');
        $data = json_decode($data,true);
        $trans_id = $data['order_no'];
        $loan = UserLoanRequest::where(['trans_id' => $trans_id, 'source' => 'r360'])->first();
        $user = User::find($loan->user_id);
        $base_info = R360UserBaseInfo::where('user_id', $user->id)->first();
        $phone_list = [];
        if(count($data['contacts']['phone_list'])>0){
            foreach ($data['contacts']['phone_list'] as $k => $v) {
                $phone_list[] = ['contactName' => $v['name'], 'phone' => $v['phone']];
            }
        }
        $user_infos = [
            'user_id' => $loan->user_id,
            'education' => R360FieldTransfer::edu_transfer($base_info->user_education),
            'company' => $data['company_name']??'',
            'work_address' => $data['company_addr_detail']??'',
            'word_phone' => $data['company_number']??'',
            'linkman_first' => $data['emergency_contact_personA_name'],
            'linkman_first_relation' => R360FieldTransfer::relation_ship_A_transfer($data['emergency_contact_personA_relationship']),
            'linkman_first_phone' => $data['emergency_contact_personA_phone'],
            'linkman_second' => $data['emergency_contact_personB_name'],
            'linkman_second_relation' => R360FieldTransfer::relation_ship_B_transfer($data['emergency_contact_personB_relationship']),
            'linkman_second_phone' => $data['emergency_contact_personB_phone'],
            'phone_address_list' => json_encode($phone_list),
        ];
        $device_info = [
            'user_id' => $loan->user_id,
            'loan_request_id' => $loan->id,
            'device_type' => strtolower($data['contacts']['platform']) == 'ios' ? 'IOS' : 'Android',
            'device_app' => '',
            'gps' => "{$data['contacts']['app_location']['lat']},{$data['contacts']['app_location']['lon']}",
        ];
        if ($device_info['device_type'] == 'IOS') {
            $device_info['device'] = $data['device_info_all']['device_model'];
            $device_info['device_os'] = $data['device_info_all']['ios_ver'];
            $device_info['device_mac'] = '';
            $device_info['device_uuid'] = $data['device_info_all']['uuid'];
        }
        if($device_info['device_type']=='Android'){
            $device_info['device'] = $data['contacts']['device_info'];
            $device_info['device_os'] = $data['device_info_all']['systemtVersion'];
            $device_info['device_mac'] = $data['device_info_all']['mac'];
            $device_info['device_imei'] = $data['device_info_all']['imei'];
        }
        $cert = UserCertOcr::where(['user_id'=>$user->id,'is_valid'=>1])->first();
        //todo 补充身份证信息
        $cert_info = [
            'domicile_address'=>$data['ID_Address_OCR']??null,
            'issuing_authority'=>$data['ID_Issue_Org_OCR']??null,
        ];
        if(!empty($data['ID_Due_time_OCR'])){
            $valid_date = explode('-',$data['ID_Due_time_OCR']);
            foreach ($valid_date as $k =>$v){
                if($v!=='长期'){
                    $valid_date[$k] = str_replace('.','-',$v);
                }
            }
            $cert_info['valid_date_begin'] = date('Y-m-d',strtotime($valid_date[0]));
            $cert_info['valid_date_end'] =$valid_date[1]=='长期'?'长期':date('Y-m-d',strtotime($valid_date[1]));
        }
        DB::beginTransaction();
        try{
            /**
             * 更新身份证信息
             */
            $cert->updateLogic($cert_info);
            /**
             * 添加用户设备信息
             */
            UserDeviceInfo::create($device_info);
            /**
             * 添加用户基础信息
             */
            UserInfo::create($user_infos);
            DB::commit();

        }catch(\Exception $e){
            DB::rollBack();
            SamLogFacade::debug("r360补充消息接口错误：".$e->getMessage());
            return r360fail('服务器错误！');
        }
        $tokens = [
            'ID_Positive'=>$data['ID_Positive'][0],
            'ID_Negative'=>$data['ID_Negative'][0],
            'photo_assay'=>$data['photo_assay'][0],
        ];
        event(new R360GetCertPicEvent($user->id,$tokens,$trans_id));
        return r360Success();
    }
}
